home *** CD-ROM | disk | FTP | other *** search
- Path: newshost.lanl.gov!tanmoy
- From: tanmoy@qcd.lanl.gov (Tanmoy Bhattacharya)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: 21 Jan 1996 17:44:04 GMT
- Organization: Los Alamos National Laboratory
- Message-ID: <TANMOY.96Jan21104404@qcd.lanl.gov>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>
- <4dpian$gij@oxy.rust.net> <9601201820.AA01752@dxmint.cern.ch>
- NNTP-Posting-Host: qcd.lanl.gov
- Mime-Version: 1.0
- Content-Type: text
- In-reply-to: Dan Pop's message of Sat, 20 Jan 1996 19:20:47 +0100
-
- --text follows this line--
- In article <9601201820.AA01752@dxmint.cern.ch> Dan Pop
- <danpop@mail.cern.ch> writes:
- <snip>
- >Given some number, there is a neat trick to generate a mask which will
- >have exactly one bit set in it. The bit set will be the least
- >significant non-zero bit in the original number:
- >
- > mask = ~number & number;
- >
- >Now, if number contained a single non-zero bit (and is therefore a
- >power of 2), mask will be equal to number. Therefore:
- >
- > if (number == (~number & number))
- > {
- > /* number is a power of 2 */
- > }
- >
- >Try it, you'll like it!
-
- I don't think so. ~number & number will _always_ give 0. -number & number
- will actually work, except for the case when number == 0. That is,
- assuming a two's complement implementation. On a one's complement or
- sign-magnitude implementation it won't work at all.
-
- Consider x = 0...0101. -x = 1...1011
- -x & x == 1. So I cannot quite figure out what was meant above.
-
- x && !(x & ~-x) is a possible solution: But since ~-x is the same as
- (x-1), this is the same as an already posted answer. (I am sorry that
- in my hurry I missed the x && bit in a previous post).
-
- Instead of calling for 2's complement arithmetic, I prefer to say that
- these should only be used for unsigned types.
-
- Cheers
- Tanmoy
- --
- tanmoy@qcd.lanl.gov(128.165.23.46) DECNET: BETA::"tanmoy@lanl.gov"(1.218=1242)
- Tanmoy Bhattacharya O:T-8(MS B285)LANL,NM87545 H:#9,3000,Trinity Drive,NM87544
- Others see <gopher://yaleinfo.yale.edu:7700/00/Internet-People/internet-mail>,
- <http://alpha.acast.nova.edu/cgi-bin/inmgq.pl>or<ftp://csd4.csd.uwm.edu/pub/
- internetwork-mail-guide>. -- <http://nqcd.lanl.gov/people/tanmoy/tanmoy.html>
- fax: 1 (505) 665 3003 voice: 1 (505) 665 4733 [ Home: 1 (505) 662 5596 ]
-